package com.example.springboot_09_websocket.server;

import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @auther cangshufeilun
 * @date 2022/4/4 10:18
 */
@ServerEndpoint("/chat-room/{username}")
@Component
public class ChatServer {

    //连接信息
    public static final Map<String, Session> ONLINE_USER_SESSIONS = new ConcurrentHashMap<>();

    @OnOpen
    public void openSession(@PathParam("username") String username, Session session) {
        ONLINE_USER_SESSIONS.put(username, session);
        String message = "欢迎用户[" + username + "] 来到聊天室！";
        System.out.println(message);
//        logger.info("用户登录："+message);
        sendMessageAll(message);
    }

    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        System.out.println(username+":"+message);
//        logger.info("发送消息："+message);
        sendMessageAll("用户[" + username + "] : " + message);
    }

    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        final RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic == null) {
            return;
        }
        try {
            basic.sendText(message);
        } catch (IOException e) {
//            logger.error("sendMessage IOException ",e);
            System.out.println(e.getMessage());
        }
    }

    public static void sendMessageAll(String message) {
//        ONLINE_USER_SESSIONS.forEach((sessionId, session) -> sendMessage(session, message));
        for(Session s:ONLINE_USER_SESSIONS.values()){
            sendMessage(s,message);
        }
    }
}
